$package('common.knowledge');
$import('common.knowledge.leftMenu');
$import('common.knowledge.knowledgeTree');
$import('common.config.category.serviceDirectoryUtils');
$import('common.config.attachment.chooseAttachment');
$import('common.config.includes.includes');
$import('common.config.category.serviceCatalog');
$import('common.security.xssUtil');
/**  
 * @author Van  
 * @constructor addKnowledge
 * @description "知识库新增"
 * @date 2010-11-17
 * @since version 1.0 
 */
common.knowledge.addKnowledge=function(){
	return {
		/**
		 * 保存新增.
		 */
		saveKnowledge:function(){
			var oEditor = CKEDITOR.instances.addKnowledgeCon;
			var content=trim(oEditor.getData());
			var title=trim($('#addKnowledge_title').val());
			var content = formatDescContent( content ) ;
			if($('#addKnowledgePanel form').form('validate')){
				if(title==''||content=='' ){
					msgAlert(i18n['knowTitleAndContentNotNull'],'info');
				}else{
					$('#addKnowledge_Content').val(content);
					if($('#addKnowledge_knowledgeStatus').attr("checked")){
						$('#addKnowledge_knowledgeStatus').val(1);
					}else{
						$('#addKnowledge_knowledgeStatus').val(0);
					}
					$.each($("#addKnowledge_contentPanel :input[attrtype='String']"),function(ind,val){
						$(this).val(common.security.xssUtil.html_encode($(this).val()));
					});
					var _param = $('#addKnowledgePanel form').serialize();
					var _url='knowledgeInfo!saveKnowledgeInfo.action';
					//进程状态
					startProcess();
					$.post(_url,_param,function(){
						//清空内容
						$('#addKnowledge_title').val("");
						$('#addKnowledge_categoryNo').val("");
						$('#addKnowledge_Category').val("");
						$('#addKnowledge_keyWords').val("");
						$('#addKnowledge_Content').val("");
						$('#addKnowledgeCon').val("");
						$('#addKnowledge_uploadedAttachments,#addKnowledge_olduploadedAttachments,#addKnowledge_fileQueue').html("");
						$('#addKnowledge_attachments').val("");
						$('#addKnowledge_knowledgeStatus').attr({'checked':false});
						$('#addKnowledge_service_dir_items_name,#addKnowledge_service_dir_items_id').val('');
						basics.tab.tabUtils.closeTab(i18n.title_request_knowledgeGrid);
						basics.tab.tabUtils.closeTab(i18n.title_request_newKnowledge);
						common.knowledge.leftMenu.showKnowledgeIndex("knowledge");
						msgShow(i18n['addSuccess'],'show');
						//进程状态
                        endProcess();
					});
				}
			}
		},
		checkKnowledgeTitle:function(){
			var title=trim($('#addKnowledge_title').val());
			var _url='knowledgeInfo!findKnowledgeByTitle.action';
			var parame = {"knowledgeDto.title":title};
			$.post(_url,parame,function(data){
				if(data != null){
					msgAlert(i18n['knowledge_title_exist'],'info');
				}else{
					common.knowledge.addKnowledge.saveKnowledge();
				}
			});
		},
		/**
		 * 保存知识库模板
		 * @param type 动作类型，是否为新增(add)
		 * */
		saveKnowledgeTemplate:function(type){
			if(type=="add"){
				$('#knowledgeTemplateId').val("");
			}
			if($('#knowledgeTemplateName form').form('validate') && $('#addKnowledgePanel form').form('validate')){
				
				var oEditor = CKEDITOR.instances.addKnowledgeCon;
				var title=trim($('#addKnowledge_title').val());
				var content=trim(oEditor.getData());
				var content = content.replace(/\s*<\/p>\s*|\s*<\/p>\s*/, '').replace(/\s*<p>\s*|\s*<\/p>\s*/, '').replace(/&nbsp;/gi, '');
				$('#addKnowledge_Content').val(content);
				if(title==='' || content===''){
					msgAlert(i18n['knowTitleAndContentNotNull'],'info');
				}else{
					$.each($("#addKnowledge_contentPanel :input[attrtype='String']"),function(ind,val){
						$(this).val(common.security.xssUtil.html_encode($(this).val()));
					});
					$('#knowledgeTemplateNameInput').val(common.security.xssUtil.html_encode($('#knowledgeTemplateNameInput').val()));
					var _param = $('#addKnowledgePanel form,#knowledgeTemplateNameAndTemplateType,#knowledgeTemplateName form').serialize();
					var url = 'knowledgeInfo!saveKnowledgeTemplate.action';
					startProcess();
					$.post(url,_param,function(){
						endProcess();
						$('#knowledgeTemplateName').dialog('close');
						if(type=="add"){
							$('#knowledgeTemplate').html("");
							common.knowledge.addKnowledge.selectKnowledgeTemplate();
							$('#templateGrid').trigger('reloadGrid');
							msgShow(i18n['saveSuccess'],'show');
						}else{
							$('#templateGrid').trigger('reloadGrid');
							msgShow(i18n['editSuccess'],'show');
						}
					});
				}
			}
		},
		/**
		 * 获取知识库模板内容，并填充在相应位置
		 * @param templateId 模板的ID
		 */
		getTemplateValue:function(templateId){

			$("#addKnowledge_service_name,#addKnowledge_olduploadedAttachments").html('');
			$('#addKnowledge_attachments').val('');
			if(templateId!=null && templateId!=""){
				$('#saveKnowledgeTemplateBtn').hide();
				$('#editKnowledgeTemplateBtn').show();
				$.post("template!findByTemplateId.action",{"templateDTO.templateId":templateId},function(data){
					$('#knowledgeTemplate').attr('value',data.templateId);
					$('#knowledgeTemplateNameInput').val(data.templateName);
					$('#knowledgeTemplateId').val(data.templateId);
					$('#addKnowledge_categoryNo').val(data.dto.categoryNo);
					$('#addKnowledge_title').val(common.security.xssUtil.html_code(data.dto.title));
					var categoryNo=data.dto.categoryNo;
					if(categoryNo!=null && categoryNo!=""){
						$.post("event!findByIdCategorys.action",{"categoryId":categoryNo},function(data){
							if(data!=null && data.eventName!=null && data.eventName!=''){
								$('#addKnowledge_Category').val(data.eventName);
							}else{
								$('#addKnowledge_Category').val('');
							}
						});
					}else{
						$('#addKnowledge_Category').val('');
					}
					if(data.dto.knowledgeStatus=="1"){
						$('#addKnowledge_knowledgeStatus').attr("checked",true);
					}else{
						$('#addKnowledge_knowledgeStatus').attr("checked",false);
					}
					$('#addKnowledge_service_dir_items_name').val(data.dto.subServiceName);
					$('#addKnowledge_service_dir_items_id').val(data.dto.serviceDirectoryItemNo);
					$('#addKnowledge_keyWords').val(common.security.xssUtil.html_code(data.dto.keyWords));
					if(CKEDITOR.instances['addKnowledgeCon']){
						var oEditor = CKEDITOR.instances.addKnowledgeCon;
						oEditor.setData(data.dto.content);
					}
					for(var key in data.dto.knowledgeServiceLi){
						$("#addKnowledge_service_name").append("<tr id=add_knowledge_"+key+"><td>"+data.dto.knowledgeServiceLi[key]+"</td><input type=hidden name='knowledgeDto.knowledServiceNo' value="+key+"><td><a onclick=common.knowledge.knowledgeTree.serviceRm("+key+")>"+i18n['deletes']+"</a><input type=hidden name=serviceDirNos value="+key+"></td></tr>");
					}
					$("#addKnowledge_olduploadedAttachments").html('');
					//附件
					$('#addKnowledge_attachments').val(data.dto.attachmentStr);
					var attrArr=data.dto.attachmentStr.split("-s-");
		    		for(var i=0;i<attrArr.length;i++){
		    			var url=attrArr[i].replace("\\", "/");
						if(url!=""){
		        			var attrArrs=url.split("==");
		        			var name=attrArrs[0];
		        			uploadSuccess(name.substr(name.lastIndexOf(".")),attrArrs[1],name,'#addKnowledge_attachments','#addKnowledge_olduploadedAttachments',"");
						}
		    		}
				});
			}else{
				$('#saveKnowledgeTemplateBtn').show();
				$('#addKnowledge_categoryNo').val("");
				$('#addKnowledge_Category').val("");
				$('#addKnowledge_title').val("");
				$('#addKnowledge_knowledgeStatus').attr("checked",false);
				$('#addKnowledge_service_dir_items_id').val("");
				$('#addKnowledge_keyWords').val("");
				if(CKEDITOR.instances['addKnowledgeCon']){
					var oEditor = CKEDITOR.instances.addKnowledgeCon;
					oEditor.setData("");
				}
				$('#editKnowledgeTemplateBtn').hide();
				$("#addKnowledge_service_name").html('');
			}
		},
		/**
		 * 选择知识库模板
		 */
		selectKnowledgeTemplate:function(){
			$('<option value="">-- '+i18n["common_pleaseChoose"]+' --</option>').appendTo("#knowledgeTemplate");
			$.post("template!findByTemplateType.action",{"templateDTO.templateType":"knowledge"},function(data){
				if(data!=null && data.length>0){
					for(var i=0;i<data.length;i++){
						$('<option value="'+data[i].templateId+'">'+data[i].templateName+'</option>').appendTo("#knowledgeTemplate");
					}
				}
			});
		},
		/**
		 * 打开填写知识库模板名字的窗口
		 */
		saveKnowledgeTemplateNameWin:function(){
			$('#knowledgeTemplateNameInput').val("");
			windows('knowledgeTemplateName');
		},
		/**
		 * 设置新增附件的相关信息
		 * @param name 附件名字
		 * @param url 附件地址
		 * @param size 附件大小
		 */
		setAddKnowledge_attachmentsStr:function(name,url,size){
			var str = $("#addKnowledge_attachments").val();
			str = str + name+"=="+url+"=="+size+"-s-";
			$("#addKnowledge_attachments").val(str);
		},
		/**
         * 刷新知识库
         */
        refresh : function () {
            $('#knowledgeGrid').trigger('reloadGrid');
            common.knowledge.leftMenu.showHotKnowledges();
            common.knowledge.leftMenu.showNewKnowledges();
            common.knowledge.leftMenu.countKnowledge();
        },
		/**
		 * 初始化加载
		 * @private
		 */
		init:function(){
			if(pageType=="template"){
				$('#saveKnowledgeBtn').hide();
			}
			common.config.includes.includes.loadServiceDirectoryItemsIncludesFile();
			common.config.includes.includes.loadCustomFilterIncludesFile();
			common.config.includes.includes.loadCategoryIncludesFile();
			$("#addKnowledge_loading").hide();
			$("#addKnowledge_contentPanel").show();

			$('#addKnowledge_Category').click(function(){
				common.knowledge.knowledgeTree.selectKnowledgeCategory('#knowledge_category_select_window','#knowledge_category_select_tree','#addKnowledge_Category','#addKnowledge_categoryNo');			
			});

			$('#saveKnowledgeBtn').click(common.knowledge.addKnowledge.checkKnowledgeTitle);
			
			
			$('#add_backToKnowledgeIndex').click(function(){
				if(pageType=='template'){
					basics.tab.tabUtils.refreshTab(i18n['title_dashboard_template'],'../pages/common/config/template/templateMain.jsp');
				}else{
					startLoading();
					common.config.includes.includes.loadServiceDirectoryItemsIncludesFile();
					common.config.includes.includes.loadCustomFilterIncludesFile();
					common.config.includes.includes.loadCategoryIncludesFile();
					common.knowledge.leftMenu.showKnowledgeIndex("knowledge");
					endLoading();
				}
			});

			$('#addKnowledge_service_dir_items_name').click(function(){
				common.config.category.serviceCatalog.selectServiceDir('#addKnowledge_service_name');
				//common.knowledge.knowledgeTree.selectKnowledgeService('#knowledge_services_select_window','#knowledge_services_select_tree','#addKnowledge_service_name','#addKnowledge_serviceNo');			
			});
			$('#saveKnowledgeTemplateBtn').click(function(){
				common.knowledge.addKnowledge.saveKnowledgeTemplateNameWin();
			});
			$('#addKnowledgeTemplateOk').click(function(){
				common.knowledge.addKnowledge.saveKnowledgeTemplate("add");
			});
			$('#editKnowledgeTemplateBtn').click(function(){
				common.knowledge.addKnowledge.saveKnowledgeTemplate("edit");
			});
			common.knowledge.addKnowledge.selectKnowledgeTemplate();
			if(editTemplateId!=""){
				$('#knowledgeTemplate').val(editTemplateId);
				setTimeout(function(){
					common.knowledge.addKnowledge.getTemplateValue(editTemplateId);
				},500);
			}
			setTimeout(function(){
				getUploader('#addKnowledge_uploadAttachments','#addKnowledge_attachments','#addKnowledge_olduploadedAttachments','addKnowledge_fileQueue');
				
				if($("#requestToKnowledge_serviceDirNo").val())
					common.config.category.serviceCatalog.fillByServiceDirs($("#requestToKnowledge_serviceDirNo").val(),"#addKnowledge_service_name");
				
				if(problem_eno){
					$.get("problem!problemToPrint.action?eno="+problem_eno,function(data){
						initCkeditor('addKnowledgeCon','full',function(){
							var oEditor = CKEDITOR.instances.addKnowledgeCon;
							oEditor.setData(data.edesc+"<hr>"+data.psolutions.remark);
						});
						$.each(data.serviceDirectoryNos,function(index,value){
							common.config.category.serviceCatalog.fillByServiceDirs(value,"#addKnowledge_service_name");
						});
						$("#addKnowledge_title").val(data.etitle);
						var attachmentstr="";
						$.each(data.psolutions.attachments,function(index,value){
							attachmentstr+="<div id="+value.url.substring(value.url.indexOf("/")+1,value.url.indexOf("."))+">" +
										common.tools.file.attachIcon.getIcon(value.attachmentName)+value.attachmentName+
										"<a href=javascript:deleteFile('"+value.url+"','#addKnowledge_olduploadedAttachments','#addKnowledge_attachments')>  "+(i18n['deletes'])+"</a></div>";
							common.knowledge.addKnowledge.setAddKnowledge_attachmentsStr(value.attachmentName,value.url,value.size);
						});
						$("#addKnowledge_olduploadedAttachments").append(attachmentstr);
					});
				}else{
					initCkeditor('addKnowledgeCon','full',function(){});
				}
				
				if($("#is_request_to_knowledge").val() == "" && problem_eno==""){
					$("#addKnowledgeCon").val("");
				}
			
			},0);
		}
		
	};
	
}();

//载入
$(document).ready(common.knowledge.addKnowledge.init);
